package com.bookstore.service.impl;

import com.bookstore.dto.BookDTO;
import com.bookstore.entity.Book;
import com.bookstore.entity.UserHistory;
import com.bookstore.repository.BookRepository;
import com.bookstore.repository.UserHistoryRepository;
import com.bookstore.service.UserHistoryService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserHistoryServiceImpl implements UserHistoryService {
    
    @Autowired
    private UserHistoryRepository userHistoryRepository;
    
    @Autowired
    private BookRepository bookRepository;
    
    @Override
    public UserHistory addHistory(Long userId, Long bookId, String actionType) {
        // 获取图书的分类ID
        Book book = bookRepository.findById(bookId).orElse(null);
        if (book == null) {
            return null;
        }
        
        UserHistory history = new UserHistory();
        history.setUserId(userId);
        history.setBookId(bookId);
        history.setCategoryId(book.getCategory().getId());
        history.setActionType(actionType);
        
        return userHistoryRepository.save(history);
    }
    
    @Override
    public List<UserHistory> getUserHistory(Long userId) {
        return userHistoryRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }
    
    @Override
    public List<Long> getUserInterestedCategories(Long userId) {
        return userHistoryRepository.findTopCategoriesByUserId(userId);
    }
    
    @Override
    public List<BookDTO> getUserViewedBooks(Long userId, int limit) {
        List<Long> bookIds = userHistoryRepository.findTopBooksByUserId(userId);
        if (bookIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 只取前limit个
        if (bookIds.size() > limit) {
            bookIds = bookIds.subList(0, limit);
        }
        
        // 获取图书详情并转换为DTO
        return bookIds.stream()
                .map(id -> bookRepository.findById(id).orElse(null))
                .filter(book -> book != null)
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public void clearUserHistory(Long userId) {
        List<UserHistory> histories = userHistoryRepository.findByUserIdOrderByCreatedAtDesc(userId);
        userHistoryRepository.deleteAll(histories);
    }
    
    // 实体转DTO的方法
    private BookDTO convertToDTO(Book book) {
        BookDTO dto = new BookDTO();
        dto.setId(book.getId());
        dto.setTitle(book.getTitle());
        dto.setAuthor(book.getAuthor());
        dto.setPublisher(book.getPublisher());
        dto.setOriginalPrice(book.getOriginalPrice());
        dto.setPrice(book.getPrice());
        dto.setStatus(book.getStatus());
        dto.setStock(book.getStock());
        dto.setDescription(book.getDescription());
        dto.setImageUrl(book.getImageUrl());
    
        // 设置分类信息
        if (book.getCategory() != null) {
            dto.setCategoryId(book.getCategory().getId());
            dto.setCategoryName(book.getCategory().getCategoryName());
        }
    
        // 设置销量和权重字段
        dto.setSalesCount(book.getSalesCount());
        dto.setHotWeight(book.getHotWeight());
        dto.setRecommendWeight(book.getRecommendWeight());
        dto.setFlashSaleWeight(book.getFlashSaleWeight());
    
        // 设置新旧程度
        dto.setDegree(book.getDegree());
        
        // 设置新增字段
        dto.setRegion(book.getRegion());
        dto.setFormat(book.getFormat());
        dto.setAgeRange(book.getAgeRange());
        dto.setConditionDesc(book.getConditionDesc());
        dto.setAppearance(book.getAppearance());
        dto.setInnerPages(book.getInnerPages());
        dto.setDisinfection(book.getDisinfection());
        dto.setStyle(book.getStyle());
        dto.setLength(book.getLength());
        dto.setBinding(book.getBinding());
        dto.setPreviewImages(book.getPreviewImages());
        
        // 如果有预览图片，转换为列表
        if (book.getPreviewImages() != null && !book.getPreviewImages().isEmpty()) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                dto.setPreviewImagesList(mapper.readValue(book.getPreviewImages(),
                        new TypeReference<List<String>>() {}));
            } catch (Exception e) {
                // 解析失败时设置为空列表
                dto.setPreviewImagesList(new ArrayList<>());
            }
        }
        
        return dto;
    }
}